package paolo.android.worldclock;


import java.util.TimeZone;
import android.text.format.Time;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class WorldClock extends Activity {
	Cursor savedTZs = null;
	ListView list = null;
	TimeZoneEntryAdapter adapter = null;
	
	SQLiteDatabase db = null;
	TimeZoneEntry current = null;
	
	boolean showedInstructions = false;
	
	Thread timeupdater = null;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        db = (new SQLiteHelper(this)).getWritableDatabase();
        list = (ListView)findViewById(R.id.savedtzlist);
        list.setOnItemLongClickListener(onListLongClick);

        populateListOfSavedTZs();
        
        /*
        timeupdater = new Thread(updateTZList);
        timeupdater.start();
        */
        
        
        
    }

    
    @Override
    public void onResume() {
    	super.onResume();
    	timeupdater = new Thread(updateTZList);
    	timeupdater.start();
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	timeupdater.stop();
    }
    
    /*
    @Override
    public void onRestart() {
    	super.onRestart();
    	populateListOfSavedTZs();
    	//timeupdater.start();
    }
    */
/*    
    @Override
    public void onResume() {
    	super.onResume();
    	timeupdater.start();
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	timeupdater.stop();
    }
    
    @Override
    public void onStop() {
    	super.onStop();
    	timeupdater.stop();
    }
    */
    
    private void populateListOfSavedTZs() {
    	if (savedTZs != null) {
    		stopManagingCursor(savedTZs);
    		savedTZs.close();
    	}
    	
    	savedTZs = TimeZoneEntry.getAll(db);
    	startManagingCursor(savedTZs);	
    	
    	if (savedTZs.getCount() == 0 && !showedInstructions) {
    		AlertDialog noTZs = new AlertDialog.Builder(this).create();
    		noTZs.setMessage("Use Menu to add time zones and long click to remove them");
    		noTZs.setButton("OK", new DialogInterface.OnClickListener() {				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					return;					
				}
			});
    		showedInstructions = true;
    		noTZs.show();
    	}
    	else {
	    	adapter = new TimeZoneEntryAdapter(savedTZs);
	    	list.setAdapter(adapter);
    	}
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(getApplication()).inflate(R.menu.option, menu);
		return super.onCreateOptionsMenu(menu);
	}    
    
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.tzadd) {
			startActivity(new Intent(WorldClock.this, AddTimeZone.class));
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
    private Runnable updateTZList = new Runnable() {
        public void run() {
        	for (;;) {
	            runOnUiThread(new Runnable() {
	                public void run () {
	                	populateListOfSavedTZs();
	                	
	                }
	            });
	            SystemClock.sleep(20000);
        	}
        }
        
    };
	
	
	
	private AdapterView.OnItemLongClickListener onListLongClick = new AdapterView.OnItemLongClickListener() {
		public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
			savedTZs.moveToPosition(position);
			current = new TimeZoneEntry(savedTZs.getString(savedTZs.getColumnIndex("tzid")));
			current.delete(db);
			savedTZs.requery();
			Toast.makeText(WorldClock.this, "Removed " + current.getId(), Toast.LENGTH_SHORT).show();
			
			return true;
		}
	}; 	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		db.close();
	}	
	
	class TimeZoneEntryAdapter extends CursorAdapter {
		TimeZoneEntryAdapter(Cursor c) {
			super(WorldClock.this, c);
		}
		
		@Override
		public void bindView(View row, Context ctxt, Cursor c) {
			TimeZoneEntryWrapper wrapper = (TimeZoneEntryWrapper)row.getTag();
			wrapper.populateFrom(c);
		}
		
		@Override
		public View newView(Context ctxt, Cursor c, ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View row = inflater.inflate(R.layout.row, parent, false);
			TimeZoneEntryWrapper wrapper = new TimeZoneEntryWrapper(row);
			
			row.setTag(wrapper);
			wrapper.populateFrom(c);
			
			return row;
		}
		
	}	
	
	class TimeZoneEntryWrapper {
		private TextView name = null;
		private TextView date = null;
		private TextView time = null;
		private View row = null;
		
		TimeZoneEntryWrapper(View row) {
			this.row = row;
		}
		
		void populateFrom(Cursor c) {
			String tzstr = c.getString(c.getColumnIndex("tzid"));
			TimeZone tz = TimeZone.getTimeZone(tzstr);
			int gmtoffset = tz.getRawOffset() / (1000*3600);
			
			Time now = new Time(tzstr);
			now.setToNow();
			String datenow = now.format("%A %B %e");
			getDate().setText(datenow);
			String timenow = now.format("%H:%M");
			getTime().setText(timenow);
			
			tzstr = tzstr.substring(tzstr.lastIndexOf("/") + 1);
			tzstr = tzstr.replaceAll("_", " ");
			getName().setText(tzstr);
			
		}
		
		TextView getName() {
			if (name == null) {
				name = (TextView)row.findViewById(R.id.name);
			}
			
			return name;
		}
		
		TextView getTime() {
			if (time == null) {
				time = (TextView)row.findViewById(R.id.time);
			}
			
			return time;
		}
		
		TextView getDate() {
			if (date == null) {
				date = (TextView)row.findViewById(R.id.date);
			}
			
			return date;
		}
	
	}
	
}